/**
 *Copyright 2013 by dragon.
 *
 *File name: FileWriter.java
 *Author:      dragon
 *Email:       fufulove2012@gmail.com
 *Blog:        http://blog.csdn.net/xidomlove
 *Version:     1.0.0
 *Date:        2013-10-9 下午5:53:19
 *Description: 
 */
package com.dragon.jaxel.bittorrent;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import com.dragon.log.Logger;

/**
 * @author dragon8
 * 
 */
public class FileWriter {

	RandomAccessFile randomAccessFile;
	FileChannel fileChannel;

	/**
	 * 
	 */
	public FileWriter() {
		// TODO Auto-generated constructor stub
	}

	public boolean open(File file) {
		try {
			randomAccessFile = new RandomAccessFile(file, "rw");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			Logger.getDefaultLogger().debug(e.getMessage());
			return false;
		}
		fileChannel = randomAccessFile.getChannel();
		return true;
	}

	public boolean truncate(long size) {
		try {
			fileChannel.truncate(size);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Logger.getDefaultLogger().debug(e.getMessage());
			return false;
		}
		return true;
	}

	public boolean close() {
		try {
			fileChannel.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Logger.getDefaultLogger().debug(e.getMessage());
		}
		try {
			randomAccessFile.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Logger.getDefaultLogger().debug(e.getMessage());
			return false;
		}
		return true;
	}

	boolean write(long position, ByteBuffer buffer) {
		try {
			fileChannel.write(buffer, position);
			return true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Logger.getDefaultLogger().debug(e.getMessage());
		}
		return false;
	}

	boolean write(long position, byte[] buffer, int offset, int len) {
		try {
			fileChannel.write(ByteBuffer.wrap(buffer, offset, len), position);
			return true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Logger.getDefaultLogger().debug(e.getMessage());
		}
		return false;
	}
}
